package com.yzyz.management.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.yzyz.bean.news.NewsBean;
import com.yzyz.bean.region.RegionBean;
import com.yzyz.bean.route.RouteGroupBean;
import com.yzyz.data.CacheFactory;
import com.yzyz.data.RegionStore;
import com.yzyz.data.RouteGroupStore;
import com.yzyz.service.NewsService;
import com.yzyz.service.RegionService;
import com.yzyz.service.RouteGroupService;
import com.yzyz.utils.CommonHandle;
import com.yzyz.utils.Config;
import com.yzyz.utils.error.ErrorBean;

/**
 * 管理员重新加载cache中的数据
 * @author David Sun
 * @Date   2010-4-18
 *
 */
public class ReloadDataController extends AbstractController {
	Log logger = LogFactory.getLog(ReloadDataController.class);
	private RegionService regionService;
	private NewsService newsService;
	
	public void setNewsService(NewsService newsService) {
		this.newsService = newsService;
	}

	public void setRegionService(RegionService regionService) {
		this.regionService = regionService;
	}

	public void setRouteGroupService(RouteGroupService routeGroupService) {
		this.routeGroupService = routeGroupService;
	}

	private RouteGroupService routeGroupService;
	
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		logger.info(CommonHandle.now() + " Admin is trying to reload data.");
		//重新加载所有的景区以及景区分组
		List<RegionBean> allRegions 	= regionService.init();
		RegionStore regionStore 		= CacheFactory.getRegionStore();
		regionStore.init(allRegions);
		//重新加载所有的行程以及行程分组
		List<RouteGroupBean> allGroups 	= routeGroupService.init();
		RouteGroupStore routeGroupStore = CacheFactory.getRouteGroupStore();
		routeGroupStore.init(allGroups);
		//重新加载所有的旅游资讯
		List<NewsBean> news = this.newsService.init(1000);
		CacheFactory.getNewsStore().init(news);
		this.writeToClient(response, ErrorBean.getSuccessMsg());
		//重新加载配置文件
		Config.init(this.getServletContext());
		return null;
	}
	
	private void writeToClient(HttpServletResponse response, String contents) throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Programa", "no-cache");
		response.setDateHeader("Expires", -1L);
		response.setContentType("text/html; charset=UTF-8");
		response.getWriter().write(contents);
		response.flushBuffer();
		response.getWriter().close();
	}
	
	

}
